package net.bat.service;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import net.bat.util.FileWrapper;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传附件有效性检查
 * 
 * @author c4w
 *
 */
@Service
public class FileCheck {
	private final Map<String, IFileCheck> cmap;
	public final static String PRE_JGJJ = "jgjj";
	public final static String PRE_JGRY = "jgry";
	// 附件最大2M
	public final static int SL_FIZE = 2048;
	public final static int JGJJ_WIDTH = 270;
	public final static int JGJJ_HEIGHT = 390;

	public FileCheck() {
		cmap = new HashMap<String, IFileCheck>();
		addCheck("EDLJGSH", new IFileCheck() {
			@Override
			public String valid(MultipartFile f) {
				// TODO checke 机构简介,机构荣誉
				String ofn = f.getOriginalFilename();
				String ftype = FileWrapper.getFileExt(ofn);
				if (f.getSize() > (SL_FIZE * 1024)) {
					return "[" + ofn + "]超出文件大小限制 " + SL_FIZE + "k";
				}
				if (!ftype.equals("jpg") && !ftype.equals("jpeg") && !ftype.equals("png")) {
					return "[" + ofn + "]文件后缀不符合要求 .jpg .jpeg .png";
				}
				if (ofn.startsWith("PRE_JGJJ")) {
					try {
						BufferedImage bimg = ImageIO.read(f.getInputStream());
						int width = bimg.getWidth();
						int height = bimg.getHeight();
						if ((width != JGJJ_WIDTH) || (height != JGJJ_HEIGHT)) {
							return "[" + ofn + "]图片尺寸不符合要求, 宽" + JGJJ_WIDTH + "高" + JGJJ_HEIGHT;
						}
					} catch (Exception e) {
						return "[" + ofn + "]图形文件损坏";
					}
				} else if (ofn.startsWith("PRE_JGRY")) {
					return null;
				}
				return "文件前缀不符合要求,必须是 jgjj 或jgry";
			}
		});
	}

	public void addCheck(String en, IFileCheck ic) {
		cmap.put(en, ic);
	}

	public String valid(String en, MultipartFile f) {
		if (!cmap.containsKey(en)) {
			return null;
		}
		return cmap.get(en).valid(f);
	}
}
